const router = require('koa-router')();
var formidable = require('formidable');
var fs = require('fs-extra')
const send = require('koa-send');
const session = require('koa-session');
var User = require("../../mongodb/schema/user.js");
const Koa = require('koa');
const app = new Koa();


router.get('/cloud/get', async (ctx, next) =>  {
    

	  let order=ctx.query.order,
	      data=ctx.query.data;

   	      
switch(order){

case 'cloudReg1712':
   	
  data=data.split(',')

   let user = new User({
			        user : data[0],                 
			        password: data[1],                     
			        zone: 0,     
			        zoneMax:10000000000,
			        logindate : new Date()                      
			   });
    const user_one = await User.findOne({ user:data[0]})

	if (user_one) {return ctx.body = false}
    
	const user_save= await user.save()		    
			
	if(user_save)
	{						    
		const user_dir=  await  fs.ensureDir('public/cloud/'+data[0])
		if(user_dir)
		{
			ctx.body=true
		}else
		{
			ctx.body=false	
		}
	}

break;
   	
   	
case 'cloudLogin':
{        
	let pw=ctx.query.password,		
    query = {
			user:ctx.query.user,
			password:pw
			};
	let callback =await User.find(query)

	if(callback){await ctx.render('cloud/view',{
									user:callback[0].user
								})
	            }
	else
	{await ctx.render('back',{
							message:'账号密码不存在'
							})
	}
}//end
break;

case 'getFile':

   	    	  let diruser=ctx.query.data;

		      const user_reddir=await fs.readdir('public/cloud/' + diruser);

   	          ctx.body=user_reddir

break;
    	
    	
case 'jumpFile':
           
       let userc=ctx.query.user;
           await  ctx.render('cloud/view',{
              	user:userc,
            })

break;
    	
    	
case 'deFile':
     let data4=ctx.query.data;       
         data4=JSON.parse(data4)

    	for(let i of data4[1]){
    		
    	 fs.remove('public/cloud/' + data4[0]+'/'+i, function(err) {
			  if (err) return console.error(err)

			}) 
    	}
    	
    	ctx.body=true
break;
    	
    	
case 'newFile':

   	{   
   		data=data.split(',')
    	let file ='public/cloud/' + data[0]+'/'+data[1]
    	if(data[1].lastIndexOf('.')==-1){
    		
	    	let user_dir=  await  fs.ensureDirSync(file)
			if(user_dir)
			{
				ctx.body=true
			}else
			{
				ctx.body=false	
			}

		}
	}
        // ctx.body=true
break;
    	
    	
    	
    	
case 'downloadFile':
  
    	down="cloud"+data.user+"/"+data.arry[0]
        ctx.attachment(down);
        //await send(ctx, down, { root: __dirname + '/public' });
    	await send(ctx, down);
    	 
break;
    	
case 'editFile':
    {
    	
    
     data=data.split(',')
    
     let uu =  await fs.rename("public/cloud/"+ data[0]+'/'+data[1],"public/cloud/"+data[0]+'/'+data[2])
    
     if(!uu)
       ctx.body=true
    
    }
break;

   	
   	default:
    console.log('case,default in order.js')
   	
   	
   }
  


  
  
});




	
	
router.post('/upload', async (ctx, next) => {
	
	let res=ctx.res,req=ctx.req;
	let name;


   let form = formidable.IncomingForm({
       encoding : 'utf-8',//上传编码
       uploadDir : "public/cloud/",//上传目录，指的是服务器的路径，如果不存在将会报错。
       keepExtensions : true,//保留后缀
       maxFieldsSize : 2 * 1024 * 1024//byte//最大可上传大小
   });
   let allFile=[];
   form.on('progress', function(bytesReceived, bytesExpected) {//在控制台打印文件上传进度
     let progressInfo = { 
        value: bytesReceived, 
        total: bytesExpected 
     }; 
     //console.log('[progress]: ' + JSON.stringify(progressInfo)); 
     //res.write(JSON.stringify(progressInfo)); 
   })
   .on('file', function (filed, file) {
   	
   
      allFile.push([filed, file]);//收集传过来的所有文件
   })
   .on('end', function() { 
      res.end('上传成功！'); 
   })
   .on('error', function(err) {
     console.error('上传失败：', err.message); 
     next(err); 
   })
   .parse(req,function(err, fields, files){
   	
   	name=fields.address
    
   	
     if(err){
        console.log(err);
     }

     
    
     
     allFile.forEach(function(file,index){
     	
     	
        // var fieldName=file[0];
        let types = file[1].name.split('.');
        // var date = new Date();
       //  var ms = Date.parse(date);
        let me1=types[0],
            me2='.'+String(types[types.length-1]);
        let mefile=me1+me2;
         
         
           time()
           function time () {
           	
           	mefile=me1+me2
           	fs.exists(form.uploadDir+"/"+name+'/'+mefile,function  (e) {
     	
				  if(e==false){
				  	
				  	fs.renameSync(file[1].path,form.uploadDir+"/"+name+'/'+mefile);//重命名文件，默认的文件名是带有一串编码的，我们要把它还原为它原先的名字。
				  	
				  		
				  	
				  }else{
				
				  	me1=me1+'(1)'
				
				  	setTimeout(time,10)
				  }
     	
           })
           	
           	
           }

    
     
     
     });
     
     
     
   }); 


ctx.body=true
	
});//end!


module.exports = router;
